<!--
  * 数据源管理
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2024-01-01 00:00:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <div class="datasource-list">
    <!-- 搜索表单 -->
    <a-card class="search-card" :bordered="false">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="数据源名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入数据源名称" allow-clear />
        </a-form-item>
        <a-form-item label="数据库类型">
          <SmartEnumSelect
            v-model:value="searchForm.type"
            enumName="DATABASE_TYPE_ENUM"
            placeholder="请选择数据库类型"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="状态">
          <SmartEnumSelect
            v-model:value="searchForm.status"
            enumName="DATASOURCE_STATUS_ENUM"
            placeholder="请选择状态"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card class="table-card" :bordered="false">
      <div class="table-operations">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          新增数据源
        </a-button>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <SmartEnumLabel :enum-name="'DATABASE_TYPE_ENUM'" :value="record.type" />
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              <SmartEnumLabel :enum-name="'DATASOURCE_STATUS_ENUM'" :value="record.status" />
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a @click="handleTest(record)">测试连接</a>
              <a @click="handleView(record)">查看</a>
              <a-popconfirm
                title="确定要删除这个数据源吗？"
                @confirm="handleDelete(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <DatasourceFormModal
      v-model:visible="modalVisible"
      :form-data="formData"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
  import { message } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { datasourceApi } from '/@/api/business/datasource/datasource-api';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
  import SmartEnumLabel from '/@/components/support/smart-enum-label/index.vue';
  import DatasourceFormModal from './components/datasource-form-modal.vue';

  const { proxy } = getCurrentInstance();

  // 搜索表单
  const searchForm = reactive({
    name: '',
    type: undefined,
    status: undefined,
  });

  // 表格数据
  const tableData = ref([]);
  const loading = ref(false);
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });

  // 弹窗控制
  const modalVisible = ref(false);
  const formData = ref({});

  // 表格列定义
  const columns = [
    {
      title: '数据源名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '数据库类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
    },
    {
      title: '主机地址',
      dataIndex: 'host',
      key: 'host',
      width: 150,
    },
    {
      title: '端口号',
      dataIndex: 'port',
      key: 'port',
      width: 100,
    },
    {
      title: '数据库名',
      dataIndex: 'databaseName',
      key: 'databaseName',
      width: 150,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
    },
  ];

  // 获取数据源列表
  const getDatasourceList = async () => {
    try {
      loading.value = true;
      const params = {
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        name: searchForm.name,
        type: searchForm.type,
        status: searchForm.status,
      };
      const res = await datasourceApi.queryPage(params);
      tableData.value = res.data.records;
      pagination.total = res.data.total;
    } catch (error) {
      message.error('获取数据源列表失败');
    } finally {
      loading.value = false;
    }
  };

  // 搜索
  const handleSearch = () => {
    pagination.current = 1;
    getDatasourceList();
  };

  // 重置
  const handleReset = () => {
    Object.assign(searchForm, {
      name: '',
      type: undefined,
      status: undefined,
    });
    pagination.current = 1;
    getDatasourceList();
  };

  // 表格变化
  const handleTableChange = (pag) => {
    pagination.current = pag.current;
    pagination.pageSize = pag.pageSize;
    getDatasourceList();
  };

  // 新增
  const handleAdd = () => {
    formData.value = {};
    modalVisible.value = true;
  };

  // 编辑
  const handleEdit = (record) => {
    formData.value = { ...record };
    modalVisible.value = true;
  };

  // 查看
  const handleView = (record) => {
    formData.value = { ...record };
    modalVisible.value = true;
  };

  // 测试连接
  const handleTest = async (record) => {
    try {
      const res = await datasourceApi.testConnection(record);
      message.success(res.data);
    } catch (error) {
      message.error('连接测试失败');
    }
  };

  // 删除
  const handleDelete = async (id) => {
    try {
      await datasourceApi.delete(id);
      message.success('删除成功');
      getDatasourceList();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 操作成功回调
  const handleSuccess = () => {
    modalVisible.value = false;
    getDatasourceList();
  };

  // 初始化
  onMounted(() => {
    getDatasourceList();
  });
</script>

<style scoped>
  .datasource-list {
    padding: 16px;
  }

  .search-card {
    margin-bottom: 16px;
  }

  .table-card {
    margin-bottom: 16px;
  }

  .table-operations {
    margin-bottom: 16px;
  }
</style> 